<template>
  <div class="code-generator-page">
    <div class="page-header">
      <h2>代码生成器</h2>
      <div class="header-actions">
        <el-button type="primary" icon="MagicStick" @click="showAIDialog = true">AI生成代码</el-button>
        <el-button type="success" icon="Download" @click="downloadCode">下载代码</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：配置面板 -->
      <el-col :span="8">
        <el-card class="config-card">
          <template #header>
            <span>生成配置</span>
          </template>

          <el-form :model="configForm" label-width="100px" label-position="top">
            <el-form-item label="生成类型">
              <el-select v-model="configForm.type" placeholder="请选择类型" @change="handleTypeChange">
                <el-option label="CRUD页面" value="crud" />
                <el-option label="表单页面" value="form" />
                <el-option label="列表页面" value="list" />
                <el-option label="详情页面" value="detail" />
                <el-option label="API接口" value="api" />
                <el-option label="数据模型" value="model" />
              </el-select>
            </el-form-item>

            <el-form-item label="模块名称">
              <el-input v-model="configForm.moduleName" placeholder="如：User" />
            </el-form-item>

            <el-form-item label="中文名称">
              <el-input v-model="configForm.chineseName" placeholder="如：用户管理" />
            </el-form-item>

            <el-form-item label="表名/路径">
              <el-input v-model="configForm.tableName" placeholder="如：sys_user" />
            </el-form-item>

            <el-divider content-position="left">字段配置</el-divider>

            <div class="fields-config">
              <div
                v-for="(field, index) in configForm.fields"
                :key="'field-' + index"
                class="field-item"
              >
                <el-input v-model="field.name" placeholder="字段名" size="small" />
                <el-select v-model="field.type" placeholder="类型" size="small">
                  <el-option label="文本" value="string" />
                  <el-option label="数字" value="number" />
                  <el-option label="日期" value="date" />
                  <el-option label="布尔" value="boolean" />
                  <el-option label="枚举" value="enum" />
                </el-select>
                <el-input v-model="field.label" placeholder="标签" size="small" />
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  size="small"
                  @click="removeField(index)"
                />
              </div>
              <el-button type="primary" size="small" @click="addField" style="width: 100%">
                <el-icon><Plus /></el-icon>
                添加字段
              </el-button>
            </div>

            <el-divider content-position="left">高级选项</el-divider>

            <el-form-item label="功能选项">
              <el-checkbox-group v-model="configForm.features">
                <el-checkbox label="search">搜索功能</el-checkbox>
                <el-checkbox label="export">导出功能</el-checkbox>
                <el-checkbox label="import">导入功能</el-checkbox>
                <el-checkbox label="batch">批量操作</el-checkbox>
                <el-checkbox label="pagination">分页</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="UI框架">
              <el-select v-model="configForm.framework">
                <el-option label="Element Plus" value="element-plus" />
                <el-option label="Ant Design Vue" value="ant-design" />
                <el-option label="Naive UI" value="naive-ui" />
              </el-select>
            </el-form-item>

            <el-button type="primary" @click="generateCode" style="width: 100%">
              <el-icon><Cpu /></el-icon>
              生成代码
            </el-button>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：代码预览 -->
      <el-col :span="16">
        <el-card class="code-card">
          <template #header>
            <div class="card-header">
              <span>代码预览</span>
              <div class="header-actions">
                <el-button-group size="small">
                  <el-button
                    v-for="tab in codeTabs"
                    :key="tab.value"
                    :type="activeCodeTab === tab.value ? 'primary' : ''"
                    @click="activeCodeTab = tab.value"
                  >
                    {{ tab.label }}
                  </el-button>
                </el-button-group>
                <el-button size="small" @click="copyCode">
                  <el-icon><DocumentCopy /></el-icon>
                  复制
                </el-button>
              </div>
            </div>
          </template>

          <div class="code-preview">
            <el-scrollbar v-if="generatedCode[activeCodeTab]" height="calc(100vh - 320px)">
              <pre><code class="language-vue">{{ generatedCode[activeCodeTab] }}</code></pre>
            </el-scrollbar>
            <el-empty v-else description="请配置后生成代码" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- AI对话框 -->
    <el-dialog v-model="showAIDialog" title="AI代码生成" width="700px">
      <el-form label-width="100px">
        <el-form-item label="需求描述">
          <el-input
            v-model="aiPrompt"
            type="textarea"
            :rows="6"
            placeholder="请描述你想要生成的功能，例如：创建一个用户管理页面，包含增删改查功能，字段有：姓名、年龄、部门、职位"
          />
        </el-form-item>
        <el-form-item label="生成语言">
          <el-select v-model="aiLanguage">
            <el-option label="Vue 3 + Element Plus" value="vue3" />
            <el-option label="React + Ant Design" value="react" />
            <el-option label="Angular + Material" value="angular" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          <el-icon><MagicStick /></el-icon>
          AI生成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 配置表单
const configForm = reactive({
  type: 'crud',
  moduleName: '',
  chineseName: '',
  tableName: '',
  fields: [
    { name: 'id', type: 'number', label: 'ID' },
    { name: 'name', type: 'string', label: '名称' }
  ],
  features: ['search', 'export', 'pagination'],
  framework: 'element-plus'
})

// 代码标签页
const codeTabs = ref([
  { label: 'Vue组件', value: 'vue' },
  { label: 'API接口', value: 'api' },
  { label: 'TypeScript', value: 'ts' },
  { label: 'SQL脚本', value: 'sql' }
])

const activeCodeTab = ref('vue')

// 生成的代码
const generatedCode = reactive({
  vue: '',
  api: '',
  ts: '',
  sql: ''
})

// AI对话框
const showAIDialog = ref(false)
const aiPrompt = ref('')
const aiLanguage = ref('vue3')
const aiGenerating = ref(false)

// 添加字段
const addField = () => {
  configForm.fields.push({
    name: '',
    type: 'string',
    label: ''
  })
}

// 删除字段
const removeField = (index) => {
  configForm.fields.splice(index, 1)
}

// 类型改变
const handleTypeChange = (type) => {
  console.log('生成类型改变', type)
}

// 生成代码
const generateCode = () => {
  if (!configForm.moduleName) {
    ElMessage.warning('请输入模块名称')
    return
  }

  // 生成Vue组件代码
  generatedCode.vue = generateVueCode()
  
  // 生成API代码
  generatedCode.api = generateAPICode()
  
  // 生成TypeScript代码
  generatedCode.ts = generateTSCode()
  
  // 生成SQL代码
  generatedCode.sql = generateSQLCode()

  ElMessage.success('代码生成成功')
}

// 生成Vue代码
const generateVueCode = () => {
  const { moduleName, chineseName, fields, features } = configForm
  
  const fieldsCode = fields.map(f => `      <el-table-column prop="${f.name}" label="${f.label}" />`).join('\n')
  
  const searchCode = features.includes('search') ? `
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        ${fields.slice(0, 3).map(f => `
        <el-form-item label="${f.label}">
          <el-input v-model="searchForm.${f.name}" placeholder="请输入${f.label}" clearable />
        </el-form-item>`).join('')}
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>` : ''

  const templatePart = `<template>
  <div class="${moduleName.toLowerCase()}-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>${chineseName}</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
        </div>
      </template>
${searchCode}
      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
${fieldsCode}
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      ${features.includes('pagination') ? `
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>` : ''}
    </el-card>
  </div>
<\/template>`

  const scriptPart = `<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const tableData = ref([])
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const searchForm = reactive({
  ${fields.slice(0, 3).map(f => `${f.name}: ''`).join(',\n  ')}
})

// 方法实现
const handleSearch = () => {
  console.log('搜索', searchForm)
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
}

const showAddDialog = () => {
  console.log('新增')
}

const handleEdit = (row) => {
  console.log('编辑', row)
}

const handleDelete = (row) => {
  console.log('删除', row)
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
}
<\/script>`

  const stylePart = `<style scoped lang="scss">
.${moduleName.toLowerCase()}-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
<\/style>`

  return templatePart + '\n\n' + scriptPart + '\n\n' + stylePart
}

// 生成API代码
const generateAPICode = () => {
  const { moduleName } = configForm
  const lowerName = moduleName.toLowerCase()
  
  return `import request from '@/utils/request'

// 获取${configForm.chineseName}列表
export function get${moduleName}List(params) {
  return request({
    url: '/api/${lowerName}/list',
    method: 'get',
    params
  })
}

// 获取${configForm.chineseName}详情
export function get${moduleName}Detail(id) {
  return request({
    url: \`/api/${lowerName}/\${id}\`,
    method: 'get'
  })
}

// 创建${configForm.chineseName}
export function create${moduleName}(data) {
  return request({
    url: '/api/${lowerName}',
    method: 'post',
    data
  })
}

// 更新${configForm.chineseName}
export function update${moduleName}(id, data) {
  return request({
    url: \`/api/${lowerName}/\${id}\`,
    method: 'put',
    data
  })
}

// 删除${configForm.chineseName}
export function delete${moduleName}(id) {
  return request({
    url: \`/api/${lowerName}/\${id}\`,
    method: 'delete'
  })
}`
}

// 生成TypeScript代码
const generateTSCode = () => {
  const { moduleName, fields } = configForm
  
  const fieldsType = fields.map(f => {
    let type = 'string'
    if (f.type === 'number') type = 'number'
    if (f.type === 'boolean') type = 'boolean'
    if (f.type === 'date') type = 'Date'
    return `  ${f.name}: ${type}`
  }).join('\n')
  
  return `// ${configForm.chineseName}类型定义
export interface ${moduleName} {
${fieldsType}
  createTime?: string
  updateTime?: string
}

// ${configForm.chineseName}查询参数
export interface ${moduleName}Query {
  ${fields.slice(0, 3).map(f => `${f.name}?: string`).join('\n  ')}
  page?: number
  pageSize?: number
}

// ${configForm.chineseName}表单
export interface ${moduleName}Form {
${fieldsType}
}`
}

// 生成SQL代码
const generateSQLCode = () => {
  const { tableName, chineseName, fields } = configForm
  
  const fieldsSQL = fields.map(f => {
    let sqlType = 'VARCHAR(255)'
    if (f.type === 'number') sqlType = 'INT'
    if (f.type === 'date') sqlType = 'DATETIME'
    if (f.type === 'boolean') sqlType = 'TINYINT(1)'
    
    return `  ${f.name} ${sqlType} COMMENT '${f.label}'`
  }).join(',\n')
  
  return `-- ${chineseName}表
CREATE TABLE ${tableName} (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT 'ID',
${fieldsSQL},
  create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  deleted TINYINT(1) DEFAULT 0 COMMENT '删除标识'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='${chineseName}表';

-- 创建索引
CREATE INDEX idx_create_time ON ${tableName}(create_time);`
}

// 复制代码
const copyCode = () => {
  const code = generatedCode[activeCodeTab.value]
  if (!code) {
    ElMessage.warning('暂无代码')
    return
  }
  
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('代码已复制到剪贴板')
  })
}

// 下载代码
const downloadCode = () => {
  if (!generatedCode.vue) {
    ElMessage.warning('请先生成代码')
    return
  }
  
  const { moduleName } = configForm
  const blob = new Blob([generatedCode.vue], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${moduleName}.vue`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('代码下载成功')
}

// AI生成
const handleAIGenerate = async () => {
  if (!aiPrompt.value) {
    ElMessage.warning('请输入需求描述')
    return
  }
  
  aiGenerating.value = true
  
  // 模拟AI生成
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  ElMessage.success('AI代码生成成功')
  aiGenerating.value = false
  showAIDialog.value = false
  
  // 自动填充表单
  configForm.moduleName = 'User'
  configForm.chineseName = '用户管理'
  configForm.tableName = 'sys_user'
  
  // 生成代码
  generateCode()
}
</script>

<style scoped lang="scss">
.code-generator-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.config-card {
  height: calc(100vh - 140px);
  overflow-y: auto;
}

.fields-config {
  .field-item {
    display: flex;
    gap: 8px;
    margin-bottom: 10px;

    .el-input,
    .el-select {
      flex: 1;
    }
  }
}

.code-card {
  height: calc(100vh - 140px);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .code-preview {
    pre {
      margin: 0;
      padding: 15px;
      background: #f5f7fa;
      border-radius: 4px;
      overflow-x: auto;

      code {
        font-family: 'Courier New', monospace;
        font-size: 13px;
        line-height: 1.6;
        color: #303133;
      }
    }
  }
}
</style>